      1  /**

      2     This example demonstrates the this reference.

      3  */

      4  public class Counter

      5  {

      6     private int value;

      7

      8     /**

      9        Constructs a counter with a given value

     10     */

     11     public Counter(int value)

     12     {

     13        this.value = value;

     14        // this. resolves the conflict between an instance variable

     15        // and a local variable with the same name

     16     }

     17

     18     public Counter()

     19     {

     20        this(0);

     21        // Invokes the Counter(int value) constructor with value = 0

     22     }

     23

     24     /**

     25        Advances the value of this counter by 1.

     26     */

     27     public void click()

     28     {

     29        this.value = this.value + 1;

     30        // Using this makes it clear that the instance variable is updated

     31     }

     32

     33     /**

     34        Gets the previous value of this counter.

     35        @return the previous value

     36     */

     37     public int getPrevious()

     38     {

     39        return getValue() - 1;

     40        // When you call a method without an object, it is invoked

     41        // on the this reference, i.e this.getValue().

     42     }

     43

     44     /**

     45        Gets the current value of this counter.

     46        @return the current value

     47     */

     48     public int getValue()

     49     {

     50        return value;

     51        // Or, if you prefer, return this.value;

     52     }

     53  }